const crypto = require('crypto')

const helper = {
  /**
   * aes加密
   * @param data 待加密内容
   * @param key 必须为32位私钥
   * @return {string}
   */
  encryption(data, key, iv = '') {
    let cipherChunks = []
    const cipher = crypto.createCipheriv('aes-256-ecb', key, iv)

    cipher.setAutoPadding(true)
    cipherChunks.push(cipher.update(data, 'utf8', 'base64'))
    cipherChunks.push(cipher.final('base64'))

    return cipherChunks.join('')
  },
  decryption(data, key, iv = '') {
    let cipherChunks = []

    const decipher = crypto.createDecipheriv('aes-256-ecb', key, iv)
    decipher.setAutoPadding(true)
    cipherChunks.push(decipher.update(data, 'base64', 'utf8'))
    cipherChunks.push(decipher.final('utf8'))

    return cipherChunks.join('')
  },
  // generates random string of characters i.e salt
  genRandomString(length) {
    return crypto.randomBytes(Math.ceil(length / 2))
      .toString('hex')
      .slice(0, length)
  },
  // hash password with sha512
  sha512(password, salt) {
    const hash = crypto.createHmac('sha512', salt)
    hash.update(password)
    return hash.digest('hex')
  }
}

module.exports = helper